﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Dynamitey;
using Microsoft.VisualBasic;
using Newtonsoft.Json.Linq;
using OfficeOpenXml.Drawing.Slicer.Style;
using org.apache.zookeeper.data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Drawing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using static AutoMapper.Internal.CollectionMapperExpressionFactory;
using static Coldairarrow.Entity.Interface.YDOrdersDTO.Orders.Delivery;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace Coldairarrow.Business.Interface
{
    public class OL_Rep_MultiReturnsInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters;
        public OL_Rep_MultiReturnsInterfaceBusiness()
        {
            this.InterfaceName = "电商退货-多平台";
            //获取字段的映射关系
            tableField = GetMapField("editRow");
            //索引字段
            Keys = GetKeys("editRow");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();


            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //执行查询前添加过滤条件
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }

        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {
                //数据库连接
                ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

                //获取此接口的所有API信息
                this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
                Base_InterfaceOption queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
                Base_InterfaceOption insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
                Base_InterfaceOption upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
                Base_InterfaceOption deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置
                //获取退货表的开始日期
                string dateForm = DateTime.Now.AddDays(-queryOption.ExcInterval).ToString("yyyy-MM-dd");
                List<string> dateList = new List<string>();
                //获取所有需要计算的数据的日期
                while (queryOption.ExcInterval != -1)
                {
                    dateList.Add(DateTime.Now.AddDays(-queryOption.ExcInterval).ToString("yyyy-MM-dd"));
                    queryOption.ExcInterval--;
                }
                string dateOfYearAge = dateForm.ToDateTime().AddYears(-1).ToString("yyyy-MM-dd");



                //获取One_Link亚马逊MSKU信息
                AMZ_MSKUInterfaceBusiness aMZ_MSKU = new AMZ_MSKUInterfaceBusiness();
                aMZ_MSKU.Filters.Clear();
                aMZ_MSKU.Filters.Add(
               //13:>,14>=15:<,16<=
               new OL_FilterDTO() { ControlId = "", DataType = 2, SpliceType = 1, FilterType = 14, Value = "" }//只查询亚马逊的MSKU
           );
                List<AMZ_MSKU> MSKUList = await aMZ_MSKU.QueryAsync<AMZ_MSKU>(aMZ_MSKU.queryOption, aMZ_MSKU.tableField, aMZ_MSKU.SqlDb);
                MSKUList.ForEach(x =>
                {
                    //SKU
                    List<AssTable> table = x.sku_lock.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.sku_lock_T = table[0];
                    x.sku_lock = x.sku_lock_T.IsNullOrEmpty() ? "" : x.sku_lock_T.sid;
                    table = x.shop.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.shop_T = table[0];
                    x.shop = x.shop_T.IsNullOrEmpty() ? "" : x.shop_T.sid;
                });

                //获取One_Link SKU信息
                OL_LocalSKUInterfaceBusiness localSKU = new OL_LocalSKUInterfaceBusiness();
                localSKU.Filters.Clear();
                localSKU.Filters.Add(
               //13:>,14>=15:<,16<=
               new OL_FilterDTO() { ControlId = "", DataType = 15, SpliceType = 1, FilterType = 14, Value = "" }//FDATE字段过滤日开始700天前到现在的数据
           );
                List<LocalSKU> localSKUList = await localSKU.QueryAsync<LocalSKU>(localSKU.queryOption, localSKU.tableField, localSKU.SqlDb);

                //获取店铺
                OL_ShopInterfaceBusiness OL_Shop = new OL_ShopInterfaceBusiness();
                OL_Shop.Filters.Add(
            new OL_FilterDTO() { ControlId = "", DataType = 29, SpliceType = 1, FilterType = 8, Value = "" }
                //new OL_FilterDTO() { ControlId = "661d1c34387bc49b7a55d06e", DataType = 15, SpliceType = 1, FilterType = 14, Value = "2024-11-24" }
                );
                List<OL_Shop> shopList = OL_Shop.Query<OL_Shop>(OL_Shop.queryOption, OL_Shop.tableField, OL_Shop.SqlDb);
                shopList.ForEach(x =>
                {
                    //平台
                    List<AssTable> table = x.Platform_.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.Platform = table.FirstOrDefault().sid;
                    //x.sku_lock = x.sku_lock_T.IsNullOrEmpty() ? "" : x.sku_lock_T.sid;
                });

                List<OL_Rep_MultiReturns> returnLsit = new List<OL_Rep_MultiReturns>();
                //多平台退货
                List<OL_Rep_MultiReturns> dates = GetMultiReturn(dateForm, MSKUList, localSKUList.Where(x => !x.SKU.IsNullOrEmpty()).ToList(), shopList);
                returnLsit.AddRange(dates);
                //获取Ozon数据
                dates = GetOzonReturn(dateForm, MSKUList, localSKUList, shopList);
                returnLsit.AddRange(dates);
                dates = GetWBReturn(dateForm, MSKUList, localSKUList, shopList);
                returnLsit.AddRange(dates);
                //dates = GetYDReturn(dateForm, MSKUList, localSKUList, shopList);
                //returnLsit.AddRange(dates);



                List<OL_Rep_MultiReturns> sourceData = new List<OL_Rep_MultiReturns>();
                sourceData = returnLsit;


                //sourceData.GroupBy(x => x.Date.ToDateTime().ToString("yyyy-MM") + x.MSKU_S + x.Seller).ForEach(x =>
                //{
                //    x.OrderBy(x => x.Date.ToDateTime()).Last().LastFlag = "Last";
                //});

                //获取目标数据
                Filters.Clear();
                Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "68084951a31d84c7f63ffe27", DataType = 15, SpliceType = 1, FilterType = 14, Value = dateForm }//FDATE字段过滤日开
            );
                List<OL_Rep_MultiReturns> targetData = await QueryAsync<OL_Rep_MultiReturns>(queryOption, tableField, SqlDb);
                foreach (var item1 in targetData)
                {
                    //MSKU
                    List<AssTable> table = item1.MSKU.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) item1.MSKU = table[0].sid;
                    else item1.MSKU = "";
                    //SKU
                    table = item1.SKU.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) item1.SKU = table[0].sid;
                    else item1.SKU = "";
                    //店铺
                    table = item1.Seller.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) item1.Seller = table[0].sid;
                    else item1.Seller = "";

                    //店铺
                    table = item1.Platform.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) item1.Platform = table[0].sid;
                    else item1.Platform = "";
                }
                if (this.State > 0 && sourceData.Count > 0)
                {
                    //更新
                    #region
                   List<OL_Rep_MultiReturns> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<OL_Rep_MultiReturns>(Keys, "RowId")).ToList();//获取交集(更新项)
                    List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                    ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                    #endregion

                    //新增
                    #region
                    List<OL_Rep_MultiReturns> insertItem = sourceData.Except(targetData, new ComparerFromKey<OL_Rep_MultiReturns>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                    List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                    ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                    #endregion

                    //删除
                    #region
                    List<OL_Rep_MultiReturns> deleteItem = targetData.Except(sourceData, new ComparerFromKey<OL_Rep_MultiReturns>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                    List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                    ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                    #endregion
                }
            }


            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }




        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //获取字段的键值做判断
                    var field = Keys.Where(x => x.TField == c.Key).ToList();
                    string isKey = "";
                    if (field.Count > 0) isKey = field.First().Type;
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value) && isKey != "N")
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }

        public List<OL_Rep_MultiReturns> GetOzonReturn(string dateForm, List<AMZ_MSKU> mskuList, List<LocalSKU> skuList, List<OL_Shop> shopList)
        {
            //退货
            List<FBOFBSReturns> returnList = SqlDb.GetListBySql<FBOFBSReturns>(@$"SELECT * FROM SD_OZ_FBOFBSReturns WHERE  return_date>='{dateForm}'");
            //订单
            List<ReportPostingsCreate> orderList = SqlDb.GetListBySql<ReportPostingsCreate>(@$"SELECT * FROM SD_OZ_ReportPostingsCreate WHERE  AcceptedForProcessing >='{dateForm}' AND Status!='Canceled' ");



            List<OL_Rep_MultiReturns> dataList = new List<OL_Rep_MultiReturns>();
            List<OL_Rep_MultiReturns> dataList_ = new List<OL_Rep_MultiReturns>();
            foreach (var item1 in orderList)
            {

                //单据状态为取消并且有退货的，或者订单状态为已交付的才进行数量计算，否则不进行计算
                OL_Rep_MultiReturns data = new OL_Rep_MultiReturns();

                var msku = mskuList.Where(x => x.seller_sku == item1.ArticleCode && x.sid == item1.SellerId);
                var sku = skuList.Where(x => x.SKU == item1.ArticleCode);
                if (!msku.IsNullOrEmpty() && msku.Count() > 0)
                {
                    data.MSKU = msku.First().RowId;
                    data.SKU = msku.First().sku_lock.IsNullOrEmpty() ? "" : msku.First().sku_lock;
                }
                else if (!sku.IsNullOrEmpty() && sku.Count() > 0)
                {
                    data.SKU = sku.First().RowId;
                }
                else
                {
                    data.MSKU = "";
                    data.SKU = "";
                }
                data.MSKU_S = item1.ArticleCode;
                data.Date = item1.AcceptedForProcessing;
                data.SellerId = item1.SellerId;
                var shop = shopList.Where(x => x.ID == item1.SellerId);

                if (!shop.IsNullOrEmpty())
                {
                    data.Seller = shop.FirstOrDefault().RowId;
                    data.Platform = shop.FirstOrDefault().Platform;
                }
                data.SalesOrder = item1.Quantity;
                //获取订单退货数据
                var ret = returnList.Where(x => x.posting_number == item1.ShipmentNumber && x.offer_id == item1.ArticleCode);
                if (!ret.IsNullOrEmpty())
                {
                    data.ReturnsOrder = ret.Sum(x => x.quantity.ToDouble()).ToString();
                }
                else
                { data.ReturnsOrder = "0"; }


                data.ID = data.MSKU_S + data.SellerId + data.Date.ToDateTime().ToString("yyyy-MM-dd");
                dataList_.Add(data);



            }
            //将ID重复的项数量合并
            var group = dataList_.GroupBy(x => x.ID);
            foreach (var item1 in group)
            {
                var first = item1.First().DeepClone();
                first.SalesOrder = item1.Sum(x => x.SalesOrder.ToDouble()).ToString();
                first.ReturnsOrder = item1.Sum(x => x.ReturnsOrder.ToDouble()).ToString();
                dataList.Add(first);
            }

            return dataList;

        }

        public List<OL_Rep_MultiReturns> GetWBReturn(string dateForm, List<AMZ_MSKU> mskuList, List<LocalSKU> skuList, List<OL_Shop> shopList)
        {
            //退货
            List<BuyersReturn> returnList = SqlDb.GetListBySql<BuyersReturn>(@$"SELECT * FROM SD_WB_BuyersReturn WHERE  CONVERT(DATE,order_dt) >='{dateForm}'");
            //订单
            List<SaleStatistics> orderList = SqlDb.GetListBySql<SaleStatistics>(@$"SELECT * FROM SD_WB_SaleStatistics WHERE  [begin] >='{dateForm}'");



            List<OL_Rep_MultiReturns> dataList = new List<OL_Rep_MultiReturns>();
            List<OL_Rep_MultiReturns> dataList_ = new List<OL_Rep_MultiReturns>();
            foreach (var item1 in orderList.Where(x => x.buyoutsCount.ToDouble() > 0))
            {

                OL_Rep_MultiReturns data = new OL_Rep_MultiReturns();

                var msku = mskuList.Where(x => x.seller_sku == item1.vendorCode && x.sid == item1.vendorCode);
                var sku = skuList.Where(x => x.SKU == item1.vendorCode);
                if (!msku.IsNullOrEmpty() && msku.Count() > 0)
                {
                    data.MSKU = msku.First().RowId;
                    data.SKU = msku.First().sku_lock.IsNullOrEmpty() ? "" : msku.First().sku_lock;
                }
                else if (!sku.IsNullOrEmpty() && sku.Count() > 0)
                {
                    data.SKU = sku.First().RowId;
                }
                else
                {
                    data.MSKU = "";
                    data.SKU = "";
                }
                data.MSKU_S = item1.vendorCode;
                data.Date = item1.begin;
                data.SellerId = "Wildberries";
                var shop = shopList.Where(x => x.ID == data.SellerId);
                if (!shop.IsNullOrEmpty())
                {
                    data.Seller = shop.FirstOrDefault().RowId;
                    data.Platform = shop.FirstOrDefault().Platform;
                }
                data.SalesOrder = item1.buyoutsCount;
                //获取订单退货数据
                var ret = returnList.Where(x => x.nm_id == item1.nmID && x.order_dt.ToDateTime().Date == item1.begin.ToDateTime().Date);
                if (!ret.IsNullOrEmpty())
                {
                    data.ReturnsOrder = ret.Count().ToString();
                }
                else
                { data.ReturnsOrder = "0"; }


                data.ID = data.MSKU_S + data.SellerId + data.Date.ToDateTime().ToString("yyyy-MM-dd");
                dataList_.Add(data);

            }
            //将ID重复的项数量合并
            var group = dataList_.GroupBy(x => x.ID);
            foreach (var item1 in group)
            {
                var first = item1.First().DeepClone();
                first.SalesOrder = item1.Sum(x => x.SalesOrder.ToDouble()).ToString();
                first.ReturnsOrder = item1.Sum(x => x.ReturnsOrder.ToDouble()).ToString();
                dataList.Add(first);
            }

            return dataList;

        }
        public List<OL_Rep_MultiReturns> GetYDReturn(string dateForm, List<AMZ_MSKU> mskuList, List<LocalSKU> skuList, List<OL_Shop> shopList)
        {
            //退货
            List<FBOFBSReturns> returnList = SqlDb.GetListBySql<FBOFBSReturns>(@$"SELECT * FROM SD_OZ_FBOFBSReturns WHERE  return_date>='{dateForm}'");
            //订单
            List<ReportPostingsCreate> orderList = SqlDb.GetListBySql<ReportPostingsCreate>(@$"SELECT * FROM SD_OZ_ReportPostingsCreate WHERE  AcceptedForProcessing >='{dateForm}'");



            List<OL_Rep_MultiReturns> dataList = new List<OL_Rep_MultiReturns>();
            List<OL_Rep_MultiReturns> dataList_ = new List<OL_Rep_MultiReturns>();
            foreach (var item1 in orderList)
            {

                OL_Rep_MultiReturns data = new OL_Rep_MultiReturns();

                var msku = mskuList.Where(x => x.seller_sku == item1.ArticleCode && x.sid == item1.SellerId);
                var sku = skuList.Where(x => x.SKU == item1.ArticleCode);
                if (!msku.IsNullOrEmpty() && msku.Count() > 0)
                {
                    data.MSKU = msku.First().RowId;
                    data.SKU = msku.First().sku_lock.IsNullOrEmpty() ? "" : msku.First().sku_lock;
                }
                else if (!sku.IsNullOrEmpty() && sku.Count() > 0)
                {
                    data.SKU = sku.First().RowId;
                }
                else
                {
                    data.MSKU = "";
                    data.SKU = "";
                }
                data.MSKU_S = item1.ArticleCode;
                data.Date = item1.AcceptedForProcessing;
                data.SellerId = item1.SellerId;
                var shop = shopList.Where(x => x.ID == item1.SellerId);
                if (!shop.IsNullOrEmpty())
                {
                    data.Seller = shop.FirstOrDefault().RowId;
                    data.Platform = shop.FirstOrDefault().Platform;
                }
                data.SalesOrder = item1.Quantity;
                //获取订单退货数据
                var ret = returnList.Where(x => x.posting_number == item1.ShipmentNumber && x.offer_id == item1.ArticleCode);
                if (!ret.IsNullOrEmpty())
                {
                    data.ReturnsOrder = ret.Sum(x => x.quantity.ToDouble()).ToString();
                }
                else
                { data.ReturnsOrder = "0"; }


                data.ID = data.MSKU_S + data.SellerId + data.Date.ToDateTime().ToString("yyyy-MM-dd");
                dataList_.Add(data);

            }
            //将ID重复的项数量合并
            var group = dataList_.GroupBy(x => x.ID);
            foreach (var item1 in group)
            {
                var first = item1.First().DeepClone();
                first.SalesOrder = item1.Sum(x => x.SalesOrder.ToDouble()).ToString();
                first.ReturnsOrder = item1.Sum(x => x.ReturnsOrder.ToDouble()).ToString();
                dataList.Add(first);
            }

            return dataList;

        }



        public List<OL_Rep_MultiReturns> GetMultiReturn(string dateForm, List<AMZ_MSKU> mskuList, List<LocalSKU> skuList, List<OL_Shop> shopList)
        {
            //退货
            OL_Rep_MultiReturnOrdersInterfaceBusiness multiReturnOrders = new OL_Rep_MultiReturnOrdersInterfaceBusiness();
            multiReturnOrders.Filters.Clear();
            multiReturnOrders.Filters.Add(
           //13:>,14>=15:<,16<=
           new OL_FilterDTO() { ControlId = "688c69af6441945281772389", DataType = 15, SpliceType = 1, FilterType = 14, Value = dateForm }//退货单的订单日期
       );
            List<OL_Rep_MultiReturnOrders> retList_A = multiReturnOrders.Query<OL_Rep_MultiReturnOrders>(multiReturnOrders.queryOption, multiReturnOrders.tableField, multiReturnOrders.SqlDb);
            List<OL_Rep_MultiReturnOrders> retList_B = retList_A.DeepClone();
            //订单
            List<order_details> orderList = SqlDb.GetListBySql<order_details>(@$"SELECT * FROM [V_EC_WW_OrderDetails] WHERE  date_create_platform >='{dateForm}' AND OLSeller IS NOT NULL AND OLSeller !=''");
            //先过滤掉已废弃的订单
            var orderList_ = orderList.Where(x => x.status != "已废弃" && x.status != "付款未完成");

            var C = orderList_.Count();
            List<OL_Rep_MultiReturns> dataList = new List<OL_Rep_MultiReturns>();

            List<OL_Rep_MultiReturns> dataList_ = new List<OL_Rep_MultiReturns>();
            //根据仓库SKU，店铺，订购日期分组
            var group = orderList_.GroupBy(x => x.product_sku_list + x.OLSeller + x.date_create_platform);
            foreach (var item1 in group)
            {
                var first = item1.First();
                OL_Rep_MultiReturns data = new OL_Rep_MultiReturns();

                data.Date = first.date_create_platform;
                data.Seller = first.OLSeller;
                data.SellerId = first.OLSeller;
                data.Platform = first.OLPlatform;
                data.MSKU_S = first.product_sku_list;

                if (data.Date.ToDateTime().ToString("yyyy-MM-dd") == "2025-05-09" && first.product_sku_list == "INSTASHOWER-7")
                {
                    var TEST = "";

                }

                var shop = shopList.Where(x => x.RowId == first.OLSeller);
                var msku = mskuList.Where(x => x.seller_sku == first.product_sku_org && x.shop == first.OLSeller);
                var sku = skuList.Where(x => x.SKU == first.product_sku_list);
                //判断仓库SKU是否能匹配到SKU
                if (!sku.IsNullOrEmpty() && sku.Count() > 0)
                {
                    data.SKU = sku.First().RowId;
                }
                //判断原平台MSKU是否能匹配到MSKU
                if (!msku.IsNullOrEmpty() && msku.Count() > 0 && data.SKU.IsNullOrEmpty() && !first.product_sku_org.Contains("+"))
                {
                    data.MSKU = msku.First().RowId;
                    data.MSKU_Org = first.product_sku_org;
                    data.SKU = msku.First().sku_lock.IsNullOrEmpty() ? "" : msku.First().sku_lock;
                }
                if (data.SKU.IsNullOrEmpty())//如果订单的原平台MSKU和仓库SKU都查不到SKU，则继续使用仓库SKU的模糊匹配和易仓ERPSKU的精确和模糊匹配
                {
                    //易仓ERPSKU的精确匹配
                    var sku_ = skuList.Where(x => x.SKU == first.platform_sku);
                    if (!sku_.IsNullOrEmpty() && sku_.Count() > 0)
                    {
                        data.SKU = sku_.OrderBy(x => x.SKU).First().RowId;
                    }
                    else if (data.SKU.IsNullOrEmpty())
                    {
                        //仓库SKU的模糊匹配
                        sku_ = skuList.Where(x => x.SKU.Contains(first.product_sku_list));
                        if (!sku_.IsNullOrEmpty() && sku_.Count() > 0)
                        {
                            data.SKU = sku_.OrderBy(x => x.SKU).First().RowId;
                        }
                    }
                    else
                    {
                        //易仓ERPSKU的模糊匹配
                        sku_ = skuList.Where(x => x.SKU.Contains(first.platform_sku));
                        if (!sku_.IsNullOrEmpty() && sku_.Count() > 0)
                        {
                            data.SKU = sku_.OrderBy(x => x.SKU).First().RowId;
                        }

                    }
                }


                //else if(!sku.IsNullOrEmpty() && sku.Count() > 0)
                //{
                //    //data.MSKU = "";
                //    data.SKU = "";
                //}
                var idList = item1.Select(x => x.op_id);
                //统计销量
                data.SalesOrder = item1.Sum(x => x.qty.ToDouble()).ToString();
                List<OL_Rep_MultiReturnOrders> orderReturns = new List<OL_Rep_MultiReturnOrders>();
                item1.ForEach(x =>
                {
                    //查询订单是否有对应的退货单
                    var temp = retList_A.Where(y => y.OrderId == x.op_id);
                    //有则将退货单加入订单退货列表，移除退货单的第二个列表中包含的订单
                    if (!temp.IsNullOrEmpty() && temp.Count() > 0)
                    {
                        //将退货单添加到退货列表中
                        orderReturns.AddRange(temp);
                        //移除退货列表B的退货单
                        temp.ForEach(x => retList_B.RemoveAll(y => x.OrderId == y.OrderId));
                    }
                });
                //统计退货
                if (orderReturns.Count > 0)
                {
                    data.ReturnsOrder = orderReturns.Sum(x => x.ReturnCount.ToDouble()).ToString();
                }
                else
                {
                    data.ReturnsOrder = "0";
                }
                data.ID = first.product_sku_list + data.SellerId + data.Date.ToDateTime().ToString("yyyy-MM-dd");
                dataList_.Add(data);
            }

            //如果退货列表还存在退货单，则通过退货单查找订单来统计销量(退货中有可能包含了废弃的订单，上面的统计不包含废弃的订单)
            if (retList_B.Count > 0)
            {
                foreach (var item1 in retList_B)
                {
                    //订单
                    if (!item1.OrderNo.IsNullOrEmpty())
                    {
                        var retOrder = orderList.Where(x => x.refrence_no.Contains(item1.OrderNo));
                        if (!retOrder.IsNullOrEmpty())
                        {
                            //获取废弃的订单
                            var disList = retOrder.Where(x => x.status == "已废弃");
                            var first = retOrder.First();
                            if (retOrder.Count() == 1)//如果订单只有1项，直接统计
                            {
                                OL_Rep_MultiReturns data = new OL_Rep_MultiReturns();
                                data.Date = item1.OrderDate;
                                data.MSKU_S = item1.SKU;
                                var sku = skuList.Where(x => x.SKU == item1.SKU);
                                if (!sku.IsNullOrEmpty() && sku.Count() > 0)
                                {
                                    data.SKU = sku.First().RowId;
                                }
                                else
                                {
                                    //data.MSKU = "";
                                    data.SKU = "";
                                }
                                data.Seller = first.OLSeller;
                                data.SellerId = first.OLSeller;
                                data.Platform = first.OLPlatform;
                                data.ReturnsOrder = item1.ReturnCount;
                                data.SalesOrder = first.qty;
                                data.ID = data.MSKU_S + data.SellerId + data.Date.ToDateTime().ToString("yyyy-MM-dd");
                                dataList_.Add(data);
                            }
                            else if (retOrder.Count() > 1 && disList.Count() != retOrder.Count())//如果订单有多个，表明是拆分过的订单，销量在前面步骤已经统计，直接拿之间的数据累加退货数量即可
                            {
                                var id = item1.SKU + first.OLSeller + item1.OrderDate.ToDateTime().ToString("yyyy-MM-dd");
                                var temp = dataList_.Where(x => x.ID == id);
                                if (!temp.IsNullOrEmpty() && temp.Count() > 0)
                                {
                                    temp.First().ReturnsOrder = (item1.ReturnCount.ToDouble() + temp.First().ReturnsOrder.ToDouble()).ToString();
                                }

                            }
                            else if (retOrder.Count() > 1 && disList.Count() == retOrder.Count())//如果全都废弃，则需要查寻到订单计算
                            {
                                var order_C = orderList.Where(x => x.op_id == item1.OrderId);
                                if (!order_C.IsNullOrEmpty() && order_C.Count() > 0)
                                {
                                    var first_C = order_C.First();
                                    OL_Rep_MultiReturns data = new OL_Rep_MultiReturns();
                                    data.Date = item1.OrderDate;
                                    data.MSKU_S = item1.SKU;
                                    var sku = skuList.Where(x => x.SKU == item1.SKU);
                                    if (!sku.IsNullOrEmpty() && sku.Count() > 0)
                                    {
                                        data.SKU = sku.First().RowId;
                                    }
                                    else
                                    {
                                        //data.MSKU = "";
                                        data.SKU = "";
                                    }
                                    data.Seller = first_C.OLSeller;
                                    data.SellerId = first_C.OLSeller;
                                    data.Platform = first_C.OLPlatform;
                                    data.ReturnsOrder = item1.ReturnCount;
                                    data.SalesOrder = first_C.qty;
                                    data.ID = data.MSKU_S + data.SellerId + data.Date.ToDateTime().ToString("yyyy-MM-dd");
                                    dataList_.Add(data);



                                }
                            }



                        }

                    }
                }
            }

            //将ID重复的项数量合并
            var group1 = dataList_.GroupBy(x => x.ID);
            foreach (var item1 in group1)
            {
                var first = item1.First().DeepClone();
                first.SalesOrder = item1.Sum(x => x.SalesOrder.ToDouble()).ToString();
                first.ReturnsOrder = item1.Sum(x => x.ReturnsOrder.ToDouble()).ToString();
                dataList.Add(first);
            }



            return dataList;

        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
